package com.tsdykj.peng.diary;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.tsdykj.peng.diary.function.DiaryApplication;
import com.tsdykj.peng.diary.function.GetDataListener;
import com.tsdykj.peng.diary.function.HttpConnectionTestTask;
import com.tsdykj.peng.diary.function.MailTask;
import com.tsdykj.peng.diary.function.PUtils;
import com.tsdykj.peng.diary.function.PathManager;
import com.tsdykj.peng.diary.function.RequestListener;
import com.tsdykj.peng.diary.function.VolleyStringRequestAsync;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MainActivity extends Activity implements View.OnClickListener {

    private final static String TAG = "MAINACTIVITY";
    private static Boolean isQuit = false;

    private ListView lstview;
    private List<Map<String, String>> jobList = new ArrayList<Map<String, String>>();
    private SimpleAdapter adapter;
    private SimpleDateFormat dateFormat;
    private String today;
    private FloatingActionsMenu plusMenu;
    private FloatingActionButton btnPersonSettings;
    private FloatingActionButton btnHistoryList;
    private FloatingActionButton btnAbout;
    private FloatingActionButton btnAdd;

    private RequestQueue requestQueue;
    private ProgressDialog progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestQueue = Volley.newRequestQueue(MainActivity.this);
        setContentView(R.layout.activity_main);

        adapter = new SimpleAdapter(this, jobList, R.layout.diary_item, new String[]{
                "title", "description"
        }, new int[]{
                R.id._diary_item_name, R.id._diary_item_content
        });

        lstview = (ListView) findViewById(R.id._lv_item_list);
        lstview.setAdapter(adapter);

        lstview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent mIntent = new Intent(MainActivity.this, job_item_edit_activity.class);
                mIntent.putExtra("_id", jobList.get(position).get("_id"));
                mIntent.putExtra("title", jobList.get(position).get("title"));
                mIntent.putExtra("description", jobList.get(position).get("description"));
                mIntent.putExtra("done_status", jobList.get(position).get("done_status"));
                mIntent.putExtra("user_id", jobList.get(position).get("user_id"));
                mIntent.putExtra("date", jobList.get(position).get("date"));

                startActivity(mIntent);
            }

        });

        lstview.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.add(0, 1, 0, getString(R.string.Edit_JobListContextMenu));
                menu.add(0, 2, 1, getString(R.string.Del_JobListContextMenu));
            }
        });

        plusMenu = (FloatingActionsMenu) findViewById(R.id.multiple_actions);

        btnPersonSettings = (FloatingActionButton)findViewById(R.id.btnPersonSettings);
        btnHistoryList = (FloatingActionButton)findViewById(R.id.btnHistoryList);
        btnAbout = (FloatingActionButton)findViewById(R.id.btnAbout);
        btnAdd = (FloatingActionButton)findViewById(R.id.job_item_add);

        btnPersonSettings.setOnClickListener(this);
        btnHistoryList.setOnClickListener(this);
        btnAbout.setOnClickListener(this);
        btnAdd.setOnClickListener(this);

        DiaryApplication.getInstance().addActivity(this);

        PUtils.CheckUpdate(MainActivity.this);

        PUtils.SetReminder(MainActivity.this, PathManager.CURRENT_USER_ID);
    }

    private void checkUserInfo() {
        Intent intent = getIntent();
        if (intent.hasExtra("user_id")) {
            String uid = intent.getStringExtra("user_id");
            if ("".equals(uid)){
                startActivity(new Intent(MainActivity.this, person_activity.class));
            }
            else
            {
                PathManager.CURRENT_USER_ID = uid;
            }

        }else if (PathManager.CURRENT_USER_ID.equals("") || PathManager.CURRENT_USER_ID == null) {
            startActivity(new Intent(MainActivity.this, person_activity.class));
        }
    }

    Handler quitHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            isQuit = false;
            return isQuit;
        }
    });

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

        switch (item.getItemId()) {
            case 1:
                Intent mIntent = new Intent(MainActivity.this, job_item_edit_activity.class);
                mIntent.putExtra("_id", jobList.get(info.position).get("_id"));
                mIntent.putExtra("title", jobList.get(info.position).get("title"));
                mIntent.putExtra("description", jobList.get(info.position).get("description"));
                mIntent.putExtra("done_status", jobList.get(info.position).get("done_status"));
                mIntent.putExtra("user_id", jobList.get(info.position).get("user_id"));
                mIntent.putExtra("date", jobList.get(info.position).get("date"));

                startActivity(mIntent);

                return true;
            case 2:

                progressDialog = ProgressDialog.show(this, getString(R.string.please_wait), getString(R.string.deleting_item), true);
                String id = jobList.get(info.position).get("_id");

                removeJobItem(id);

                return true;

            default:
                return true;
        }
    }

    private void checkTodayMailed() {

        if  (PathManager.CURRENT_USER_ID.equals("") || PathManager.CURRENT_USER_ID == null){
            return;
        }
        final String url = PathManager.Host + "excelfile/count/sent/" + PathManager.CURRENT_USER_ID + "/" + today;
        new VolleyStringRequestAsync(this, url, new RequestListener() {
            @Override
            public void ProcessData(String data) {
                Log.d("checkTodayMailed", url);
                Log.d("checkTodayMailed", data);

                if (data.indexOf("0")>0){
                    PUtils.setTodayMailed(MainActivity.this, false);
                }
                else{

                    if (PUtils.getTodayMailed(MainActivity.this)){

                    }
                    else{
                        findViewById(R.id.main_menu_send_job_mail).setVisibility(View.GONE);
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setMessage(getString(R.string.already_mailed_today));
                        builder.setPositiveButton(R.string.ok, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();

                        PUtils.setTodayMailed(MainActivity.this, true);
                    }
                }
            }
        }).Execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_menu_send_job_mail:

                if (jobList.size() > 0) {
                    progressDialog = ProgressDialog.show(MainActivity.this, getString(R.string.please_wait), getString(R.string.sending_mail), true);
                    postData();
                } else {
                    Toast.makeText(getApplicationContext(),
                            getString(R.string.no_job_item_prompt), Toast.LENGTH_SHORT).show();
                }

                return true;

//            case R.id.main_menu_exit:
//                this.finish();
//                return true;
//            case R.id.main_menu_person_info:
//                Intent mIntent = new Intent(MainActivity.this, person_activity.class);
//                startActivity(mIntent);
//                return true;
//            case R.id.main_menu_about:
//                Intent nIntent = new Intent(MainActivity.this, about_webview_activity.class);
//                startActivity(nIntent);
//                return true;
//            case R.id.main_menu_diary_history:
//                Intent hIntent = new Intent(MainActivity.this, history_activity.class);
//                startActivity(hIntent);
//                return true;
            default:
                return super.onOptionsItemSelected(item);

        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
        today = dateFormat.format(new Date());

        new HttpConnectionTestTask(new GetDataListener() {
            @Override
            public void GetData(boolean online) {
                if (online) {
                    checkUserInfo();
                    getData();
                    checkTodayMailed();
                } else {
                    //Toast.makeText(getApplicationContext(), getString(R.string.serveroffline), Toast.LENGTH_LONG).show();
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setMessage(getString(R.string.serveroffline));
                    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            DiaryApplication.getInstance().exit();
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            }
        }).execute();
    }

    @Override
    public void onClick(View v) {

        Intent mIntent = null;

        switch (v.getId()){
            case R.id.job_item_add:
                mIntent = new Intent(MainActivity.this, job_item_edit_activity.class);
                break;
            case R.id.btnPersonSettings:
                mIntent = new Intent(MainActivity.this, person_activity.class);
                break;
            case R.id.btnHistoryList:
                mIntent = new Intent(MainActivity.this, history_activity.class);
                break;
            case R.id.btnAbout:
                mIntent = new Intent(MainActivity.this, about_webview_activity.class);
                break;
        }

        plusMenu.collapse();
        if (mIntent!=null) startActivity(mIntent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isQuit) {
                isQuit = true;
                Toast.makeText(getApplicationContext(), getString(R.string.press_twice_quit_program), Toast.LENGTH_SHORT).show();
                quitHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                DiaryApplication.getInstance().exit();
            }
        }
        return false;
    }

    public void postData() {

        if (PathManager.CURRENT_USER_ID == null || PathManager.CURRENT_USER_ID.length() <= 0) {
            Toast.makeText(getApplicationContext(),
                    "Can not get user_id, please contact the developer", Toast.LENGTH_SHORT).show();
            return;
        }

        new MailTask(new GetDataListener() {
            @Override
            public void GetData(boolean online) {
                if (online) {
                    getData();
                } else {
                    Toast.makeText(MainActivity.this, R.string.serveroffline, Toast.LENGTH_SHORT).show();
                }
            }
        }).execute(PathManager.Host + "excel", today);
    }

    private void getData() {

        if (PathManager.CURRENT_USER_OBJECT_ID == null || PathManager.CURRENT_USER_OBJECT_ID.length() <= 0) {
            return;
        }

        String url = PathManager.Host + "jobs/nobuild/" + PathManager.CURRENT_USER_ID + "/" + today;

        Log.d(TAG, url);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                try {

                    jobList.clear();
                    for (int i = 0; i < response.length(); i++) {
                        JSONObject item = (JSONObject) response.get(i);

                        Map<String, String> map = new HashMap<String, String>();
                        map.put("_id", item.get("_id").toString());
                        map.put("title", item.getString("title"));
                        map.put("description", item.getString("description"));
                        map.put("done_status", item.getString("done_status"));
                        map.put("user_id", item.getString("user_id"));
                        map.put("date", item.getString("date"));
                        jobList.add(map);
                    }
                    Log.d(TAG, jobList.toString());
                    adapter.notifyDataSetChanged();
                    if (null != progressDialog)
                        progressDialog.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (progressDialog != null) progressDialog.dismiss();
                String error_msg = (error.getMessage() == null || error.getMessage().equals("")) ? error.toString() : error.getMessage();
                VolleyLog.d(TAG, "Error: " + error_msg);
                Toast.makeText(getApplicationContext(),
                        error_msg, Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(jsonArrayRequest);
    }

    private void removeJobItem(String id) {
        String url = PathManager.Host + "jobs/" + id;

        StringRequest request = new StringRequest(Request.Method.DELETE, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response.toString());
                getData();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String error_msg = (error.getMessage() == null || error.getMessage().equals("")) ? "" : error.getMessage();
                VolleyLog.d(TAG, "Error: " + error_msg);
                Toast.makeText(getApplicationContext(),
                        error_msg, Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);
    }
}
